<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="inet.db.tennis.TennisChampion"%>
<%@page import="inet.db.tennis.TennisMatch"%>
<%@page import="inet.util.DateTime"%>
<%@page import="inet.db.tennis.buffer.TennisChampionBuffer"%>
<%@page import="inet.db.tennis.buffer.TennisBuffer"%>
<%@page import="inet.db.tennis.TennisPhase"%>
<%@page import="java.math.BigDecimal"%>
<%@page import="inet.db.tennis.TennisRound"%>
<%@page import="inet.db.tennis.TennisPlayer"%>
<%@page import="inet.db.tennis.TennisConst"%>
<%@page import="inet.util.StringTool"%>
<jsp:useBean id="tennisChampionDAO" class="inet.db.tennis.TennisChampionDAO" scope="session"/>
<jsp:useBean id="tennisMatchDAO" class="inet.db.tennis.TennisMatchDAO" scope="session"/>
<jsp:useBean id="tennisPhaseDAO" class="inet.db.tennis.TennisPhaseDAO" scope="session"/>
<jsp:useBean id="tennisRoundDAO" class="inet.db.tennis.TennisRoundDAO" scope="session"/>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Danh sách trận đấu</title>
    <link rel="stylesheet" type="text/css" href="<%= request.getContextPath() %>/admin/tennis/css/reset.css" media="screen" />
    <link rel="stylesheet" type="text/css" href="<%= request.getContextPath() %>/admin/tennis/css/text.css" media="screen" />
    <link rel="stylesheet" type="text/css" href="<%= request.getContextPath() %>/admin/tennis/css/grid.css" media="screen" />
    <link rel="stylesheet" type="text/css" href="<%= request.getContextPath() %>/admin/tennis/css/layout.css" media="screen" />
    <link rel="stylesheet" type="text/css" href="<%= request.getContextPath() %>/admin/tennis/css/nav.css" media="screen" />
    <!--[if IE 6]><link rel="stylesheet" type="text/css" href="css/ie6.css" media="screen" /><![endif]-->
    <!--[if IE 7]><link rel="stylesheet" type="text/css" href="css/ie.css" media="screen" /><![endif]-->
    <link href="<%= request.getContextPath() %>/admin/tennis/css/table/demo_page.css" rel="stylesheet" type="text/css" />
    <!-- BEGIN: load jquery -->
    <script src="<%= request.getContextPath() %>/admin/tennis/js/jquery-1.6.4.min.js" type="text/javascript"></script>
    <script type="<%= request.getContextPath() %>/admin/tennis/text/javascript" src="js/jquery-ui/jquery.ui.core.min.js"></script>
    <script src="<%= request.getContextPath() %>/admin/tennis/js/jquery-ui/jquery.ui.widget.min.js" type="text/javascript"></script>
    <script src="<%= request.getContextPath() %>/admin/tennis/js/jquery-ui/jquery.ui.accordion.min.js" type="text/javascript"></script>
    <script src="<%= request.getContextPath() %>/admin/tennis/js/jquery-ui/jquery.effects.core.min.js" type="text/javascript"></script>
    <script src="<%= request.getContextPath() %>/admin/tennis/js/jquery-ui/jquery.effects.slide.min.js" type="text/javascript"></script>
    <script src="<%= request.getContextPath() %>/admin/tennis/js/jquery-ui/jquery.ui.mouse.min.js" type="text/javascript"></script>
    <script src="<%= request.getContextPath() %>/admin/tennis/js/jquery-ui/jquery.ui.sortable.min.js" type="text/javascript"></script>
    <script src="<%= request.getContextPath() %>/admin/tennis/js/table/jquery.dataTables.min.js" type="text/javascript"></script>
    <!-- END: load jquery -->
    <script type="text/javascript" src="<%= request.getContextPath() %>/admin/tennis/js/table/table.js"></script>
    <script src="<%= request.getContextPath() %>/admin/tennis/js/setup.js" type="text/javascript"></script>
    <script src="score.js"></script>
    <script src="status.js"></script>
    <script type="text/javascript">

        $(document).ready(function () {
            setupLeftMenu();

            var oTable = $('.datatable').dataTable();
            oTable.fnSort( [ [1,'asc'] ] );
			setSidebarHeight();
        });
    </script>
    <script type="text/javascript">
    	function f_delete_select_item() {
    		document.formListMatch.action.value = 'delete_selected';
    		document.formListMatch.submit();
    	}
    	function f_delete_item(item_del) {
    		document.formListMatch.item_del.value = item_del; 
    		document.formListMatch.action.value = 'delete_item';
    		document.formListMatch.submit();
    	}
    </script>
</head>
<body>
    <div class="container_12">
        <%@ include file="../include/header.jsp" %>
        <% 
			String sChampionCode = request.getParameter("slbChampion");
		   String sPhase = request.getParameter("slbPhase");
		   String sRound = request.getParameter("slbRound");
		
		   String sOrderByChampion = request.getParameter("orderByChampion");
		   //String sFrom11h = request.getParameter("from11h"); //tu 11h hom nay den 11h hom sau
		
		   boolean orderByChampion = false;
		   if (sOrderByChampion != null && sOrderByChampion.length() >= 1) {
		       orderByChampion = true;
		   }
		
		   String sYear = request.getParameter("yearSelect");
		   String sMonth = request.getParameter("monthSelect");
		   String sDay = request.getParameter("daySelect");
		
		   DateTime dt = new DateTime();
		   if ((sYear == null)  || "".equals(sYear))  sYear = String.valueOf(dt.getYear());
		   if ((sMonth == null) || "".equals(sMonth)) sMonth = String.valueOf(dt.getMonth());
		   if (((sDay == null)  || "".equals(sDay)) && dt.getHour() < 11)   
		       sDay = String.valueOf(dt.getDay()-1);
		   else if(((sDay == null)  || "".equals(sDay)) && dt.getHour() >= 11)
		   	   sDay = String.valueOf(dt.getDay());	
		   	   	
		
		   if ("0".equals(sChampionCode)) sChampionCode = null;
		   if (sPhase == null) sPhase = "0";
		   if ("0".equals(sRound)) sRound = null;
		   if ("0".equals(sYear))  sYear = null;
		   if ("0".equals(sMonth)) sMonth = null;
		   if ("0".equals(sDay))   sDay = null;
			//Vector<TennisMatch> vTennisMatch = tennisMatchDAO.findAll();
			TennisChampion championSelected = null;
			if(sChampionCode != null) {
				championSelected = TennisBuffer.getChampionFromCode(sChampionCode);
				if(championSelected == null) {
					championSelected = TennisBuffer.reloadChampion(sChampionCode);
				}
			}
			String sAction = request.getParameter("action");
			// Delete selected rows
    		if(sAction != null && "delete_selected".equals(sAction)) {
    			String[] selected = request.getParameterValues("chkID");
    			if (selected != null && selected.length > 0) {
		            for (int i = 0; i < selected.length; i++) {
						tennisMatchDAO.deleteRow(new BigDecimal(selected[i]));
		            }
		        }
    		} else if(sAction != null && "delete_item".equals(sAction)) {
    			String itemSelected = request.getParameter("item_del");
    			if(itemSelected != null && StringTool.isNumberic(itemSelected)) {
    				tennisMatchDAO.deleteRow(new BigDecimal(itemSelected)); 
    			}
    		}
			Vector<TennisMatch> vMatch = null;
			if(sDay == null) {
				vMatch = tennisMatchDAO.findMatchListNew(sChampionCode, sRound, sDay, sMonth, sYear, orderByChampion);
			} else {
				vMatch = tennisMatchDAO.findMatchList(sChampionCode, sRound, sDay, sMonth, sYear, orderByChampion);
			}

        %>
        <div class="grid_10">
            <div class="box round first grid">
                <h2>Danh sách trận đấu</h2>
                <div class="block">
                	<form name="formListMatch" method="post">
                		<input name="action" type="hidden" />
                		<input name="item_del" type="hidden" />
                		<table class="form" style="text-align: center;">
                			<tr>
                				<td>
                					<a href="index.jsp">Giải đấu:</a>
                					<select id="select" name="slbChampion" onchange='document.formListMatch.action.value="NOTHING";document.formListMatch.submit();'>
                						<option value="0"> - Tất cả - </option>
                						<%
									        //Lay ten cac giai -CODE1
											 //Cache cac GIAI DAU tren bo nho, tranh truy cap DB nhieu lan.
										     Collection cChampions = TennisBuffer.getChampionList();
											 if (cChampions == null) {
												cChampions = tennisChampionDAO.findChampionRunning();
											 }
									         if (cChampions != null && cChampions.size() > 0) {
									             TennisChampion champion = null;
									             String selected = "";
									             int i=0;
									             for(Iterator it = cChampions.iterator(); it.hasNext();i++){
									                 champion = (TennisChampion)it.next();
									                 if (champion == null) continue;
									                 //Show current code
									                 if (champion.getCode().equals(sChampionCode)) {
									                     selected="selected";
									                 } else{
									                     selected="";
									                 }
									         %>
									         	 <%--Gia tri nhan duoc sau khi submit form la championCode --%>
									        	 <option value="<%=champion.getCode()%>" <%=selected%>> <%=champion.getName()%></option>
									         <%
									            } //for
									         }//if
										%>
                					</select>
                					<a href="#">Giai đoạn:</a>
                					<select id="select" name="slbPhase" onchange='document.formListMatch.action.value="NOTHING";document.formListMatch.submit();'>
                						<option value="0"> - Tất cả - </option>
                						<%
                						 if (championSelected != null) {
									         Collection cPhase = tennisPhaseDAO.findAll(championSelected.getCode(), championSelected.getCurrentSeason());
									         String selectedP = "";
									         TennisPhase phase = null;
									         if(cPhase != null && !cPhase.isEmpty()) {
										         for(Iterator it = cPhase.iterator(); it.hasNext();) {
										             phase = (TennisPhase) it.next();
										             if (phase == null) continue;
										             if(phase.getId().toString().equals(sPhase)) {
										                 selectedP="selected";
										             } else {
										                 selectedP="";
										             }
								        %>
								              <option value="<%=phase.getId()%>" <%=selectedP%>> <%=phase.getPhaseName()%></option>
								        <%
								          	 	}//for
								          	 }//if
								          }//if
								        %>
                					</select>
                					<a href="#">Vòng đấu:</a>
                					<select id="select" name="slbRound">
                						<option value="0"> - Tất cả - </option>
                						<%
								         Collection cRounds = tennisRoundDAO.findAll(new BigDecimal(sPhase));
								         String selectedR = "";
								         TennisRound  round = null;
								         for(Iterator it = cRounds.iterator(); it.hasNext();) {
								             round = (TennisRound) it.next();
								              if (round == null) continue;
								              if(round.getRoundCode().equals(sRound)) {
								                  selectedR="selected";
								              } else {
								                  selectedR="";
								              }
								        %>
								              <option value="<%=round.getRoundCode()%>" <%=selectedR%>> <%=round.getRoundCode()%></option>
								        <%
								          }//for
								        %>
                					</select>
                					<font color="#000080" face="Tahoma" size="2"> Ngày</font>
                					<select name="daySelect" size="1">
            							<option value="0">Tất cả</option>
            							<%
								            String selectedDay="";
								            int iDay = (sDay != null ? Integer.parseInt(sDay) : 0);
								            for (int i = 1; i <= 31; i++) {
								                if(i == iDay) selectedDay="selected";
								                else selectedDay="";
								        %>
								        <option value="<%=i%>" <%=selectedDay%>> <%=String.valueOf(i)%></option>
								        <%
								            }
								        %>
            						</select>
                					<font color="#000080" face="Tahoma" size="2"> Tháng</font>
                					<select name="monthSelect" size="1">
            							<option value="0">Tất cả</option>
            							<%
								            String selectedM = "";
								            int iMonth = (sMonth != null ? Integer.parseInt(sMonth) : 0);
								
								            for (int i = 1; i <= 12; i++) {
								                if(i == iMonth) selectedM="selected";
								                else selectedM="";
								       %>
										<option value="<%=i%>" <%=selectedM%>> <%=String.valueOf(i)%></option>
								       <%
								            }
								       %>
            						</select>
            						<font color="#000080" face="Tahoma" size="2">Năm</font>
							        <select name="yearSelect" size="1" id="cYear" style="font-family:Arial, Tahoma">
							            <option value="0">Tất cả</option>
							        <%
							            String selectedYear = "";
							            for (int i=2012; i< 2018 ;i++){
							            	if ((sYear != null) && (i==Integer.parseInt(sYear)))
							                selectedYear="selected";
							            	else selectedYear="";
							        %>
							      		<option value="<%=i%>" <%=selectedYear%>> <%=i%></option>
							        <%
							            }
							        %>
							        </select>
							        <input type="checkbox" name="orderByChampion" value="1" <%=(orderByChampion ? "checked":"")%> /> Sắp xếp theo giải đấu
     								<button type="button" onclick="document.formListMatch.action.value='FIND';document.formListMatch.submit();" class="btn btn-grey">Tìm kiếm</button>
                				</td>
                			</tr>
                		</table>
	                    <table class="data display datatable" id="example">
							<thead>
								<tr>
									<th style="width: 5%;">STT</th>
									<th style="width: 5%;">Giờ</th>
									<th style="width: 10%;">Mã giải</th>
									<th style="width: 10%;">Tên giải</th>
									<th style="width: 5%;">Vòng</th>
									<th style="width: 5%;">Score</th>
									<th style="width: 10%;text-align: center;">Tay vợt 1</th>
									<th style="width: 5%;">Tỷ số</th>
									<th style="width: 10%;text-align: center;">Tay vợt 2</th>
									<th style="width: 5%;">Score</th>
									<th style="width: 10%;">Trạng thái</th>
									<th style="width: 5%;">Sửa</th>
									<th style="width: 5%;">Xóa</th>
								</tr>
							</thead>
							<tbody>
								<% 
									if(vMatch != null && !vMatch.isEmpty()) {
										TennisMatch match = null;
										int i = 0;
										String seasonName = "";
										TennisPlayer player1 = null;
										TennisPlayer player2 = null;
										DateTime matchDate = null;
										String lastMatchDate = "";
										
										for (Iterator it = vMatch.iterator(); it.hasNext(); i++) {
											match = (TennisMatch)it.next();
											if( match == null ) continue;
											player1 = (TennisPlayer) TennisBuffer.getPlayerFromId(match.getFirstPlayerId());
											player2 = (TennisPlayer) TennisBuffer.getPlayerFromId(match.getSecondPlayerId());
											matchDate = new DateTime(match.getMatchDate());
								            //if(!lastMatchDate.equals(matchDate.getDay()+"/"+matchDate.getMonth())){
								            //	lastMatchDate = matchDate.getDay()+"/"+matchDate.getMonth();
												// Chưa hiển thị
								            //}
								%>
								<tr class="gradeA" <%= match.getIsMatchInv() == 1 ? "style=\"background-color: #FFCC99;\"":"" %>>
									<td>
										<%= i+1 %>
									</td>
									<td><%=(matchDate.getHour()+"h"+matchDate.getMinute()+"' ") +" "+ matchDate.getDay()+"/"+matchDate.getMonth()%></td>
									<td><%= match.getChampionCodeSMS() %></td>
									<td><%= match.getChampionName() %></td>
									<td><%= match.getRound() %></td>
									<td>
										[<a href="javascript: goal('firstGoal_<%=match.getId()%>','<%=((player1 != null ? player1.getName():"Tay vợt 1") + " : " + (player2 != null ? player2.getName():"Tay vợt 2") )%>','firstGoal_<%=match.getId()%>','secondGoal_<%=match.getId()%>')">+</a>][<a href="javascript: nogoal('firstGoal_<%=match.getId()%>','<%=((player1 != null ? player1.getName():"Tay vợt 1") + " : " + (player2 != null ? player2.getName():"Tay vợt 2") )%>','firstGoal_<%=match.getId()%>','secondGoal_<%=match.getId()%>')">--</a>]
									</td>
									<td style="text-align: right;padding-right: 5px;"><%= player1 != null ? player1.getName():"" %></td>
									<td style="background-color: #FFFF33;font-size: 17px;text-align: center;font-weight: bold;">
										<span id="firstGoal_<%=match.getId()%>"><%= match.getFirstScore() %></span>
										 :
										 <span id="secondGoal_<%=match.getId()%>"><%=match.getSecondScore() %></span>
									</td>
									<td><%= player2 != null ? player2.getName():"" %></td>
									<td>
										[<a href="javascript: goal('secondGoal_<%=match.getId()%>','<%=((player1 != null ? player1.getName():"Tay vợt 1") + " : " + (player2 != null ? player2.getName():"Tay vợt 2") )%>','firstGoal_<%=match.getId()%>','secondGoal_<%=match.getId()%>')">+</a>][<a href="javascript: nogoal('secondGoal_<%=match.getId()%>','<%=((player1 != null ? player1.getName():"Tay vợt 1") + " : " + (player2 != null ? player2.getName():"Tay vợt 2") )%>','firstGoal_<%=match.getId()%>','secondGoal_<%=match.getId()%>')">--</a>]
									</td>
									<td>
								        <select name="cboStatus_<%=match.getId()%>" style="font-family:Arial,Tahoma; font-size=8pt"
								         onchange="updateSts('<%=match.getId()%>', ''+this.value+'', '_liveFilter_<%=match.getId()%>', '<%=( (player1 != null ? player1.getName():"Tay vợt 1") + " - " + (player2 != null ? player2.getName():"Tay vợt 2") )%>')">
								                <option value=<%=TennisConst.MATCH_STATUS_CHUA_DANH %> <%=(TennisConst.MATCH_STATUS_CHUA_DANH == match.getStatus()?"selected":"") %> >Ch.đánh</option>
								                <option value=<%=TennisConst.MATCH_STATUS_SET1 %> <%=(TennisConst.MATCH_STATUS_SET1 == match.getStatus()?"selected":"") %>>Set 1</option>
								                <option value=<%=TennisConst.MATCH_STATUS_SET2 %> <%=(TennisConst.MATCH_STATUS_SET2 == match.getStatus()?"selected":"") %>>Set 2</option>
								                <option value=<%=TennisConst.MATCH_STATUS_SET3 %> <%=(TennisConst.MATCH_STATUS_SET3 == match.getStatus()?"selected":"") %>>Set 3</option>
								                <option value=<%=TennisConst.MATCH_STATUS_SET4 %> <%=(TennisConst.MATCH_STATUS_SET4 == match.getStatus()?"selected":"") %>>Set 4</option>
								                <option value=<%=TennisConst.MATCH_STATUS_SET5 %> <%=(TennisConst.MATCH_STATUS_SET5 == match.getStatus()?"selected":"") %>>Set 5</option>
								                <option value=<%=TennisConst.MATCH_STATUS_KET_THUC %> <%=(TennisConst.MATCH_STATUS_KET_THUC == match.getStatus()?"selected":"") %>>K.thúc</option>
								                <option value=<%=TennisConst.MATCH_STATUS_HOAN %> <%=(TennisConst.MATCH_STATUS_HOAN == match.getStatus()?"selected":"") %>>Hoãn</option>
								        </select>
								    </td>
									<td>
										<a href="edit-match.jsp?id=<%= match.getId() %>">
											<img style="vertical-align: middle;" src="<%= request.getContextPath() %>/admin/tennis/img/cog.png" />
										</a>
									</td>
									<td>
										<a href="javascript:void(0);" onclick="if(confirm('Bạn có chắc chắn muốn xóa ??? ')){f_delete_item(<%= match.getId() %>);}">
											<img style="vertical-align: middle;" src="<%= request.getContextPath() %>/admin/tennis/img/cross.png" />
										</a>
									</td>
								</tr>
								<% 
										}// for
									} // if
								%>
							</tbody>
						</table>
					</form>
					<a href="add-match.jsp" class="btn-mini btn-black btn-plus" title="Thêm mới"><span></span>Add</a>
					<br />
					<br />
					<a class="condition"></a> &nbsp;&nbsp;&nbsp;<strong>Trận đấu điều kiện</strong> (trận đấu này được tạo để đặc cách cho 1 tay vợt vào thẳng vòng trong)
                </div>
            </div>
        </div>
        <div class="clear">
        </div>
    </div>
    <%@ include file="../include/footer.jsp" %>
</body>
</html>
<script language="JAVASCRIPT">
	function goal(gid, match, goal1, goal2){
		var g1 = document.getElementById(goal1).innerHTML;
		var g2 = document.getElementById(goal2).innerHTML;
		if (gid.indexOf("first") >= 0)
			g1++;
		else if (gid.indexOf("second") >= 0)
			g2++;
		match = match.replace("'","\'");
		match = match.replace(":"," [ " + g1 + " : " + g2 + " ] ");
		if (!confirm(match + " ?")){
			return;
		}
		var goal = document.getElementById(gid).innerHTML;
		goal++;
		document.getElementById(gid).innerHTML = goal;
		updateGoal(gid,goal);
	}

	function nogoal(gid, match, goal1, goal2){
		var g1 = document.getElementById(goal1).innerHTML;
		var g2 = document.getElementById(goal2).innerHTML;
		if (gid.indexOf("first") >= 0 && g1 > 0)
			g1--;
		else if (gid.indexOf("second") >= 0 && g2 > 0)
			g2--;
		match = match.replace(":"," [ " + g1 + " : " + g2 + " ] ");
		if (!confirm(match + "?")){
			return;
		}
		var goal = document.getElementById(gid).innerHTML;
		if (goal>0){
			goal--;
			updateGoal(gid,goal);
		}
		document.getElementById(gid).innerHTML = goal;
	}
	function updateSts(id, status, target, match){
	    var temp = "";
	    switch (status) {
	        case "0": temp = "CHƯA ĐÁNH"; break;
	        case "1": temp = "SET 1"; break;
	        case "2": temp = "SET 2"; break;
	        case "3": temp = "SET 3"; break;
	        case "4": temp = "SET 4"; break;
	        case "5": temp = "SET 5"; break;
	        case "6": temp = "KẾT THÚC"; break;
	        case "8": temp = "HOÃN"; break;
	        default : temp = "";
	    }
	    if (!confirm("Thay đổi trạng thái trận: " + match + " --> ["+temp+"] ?")){
	    	return;
	    }
	    updateStatus(id, status, target);
	}
</script>